import datetime
import random

from django.db import models

from sportsground.utils.baseModels import BaseModels, IntegerChoices


class OrderGoods(BaseModels):
    class Meta():
        db_table = 'order_goods'
        verbose_name = '商品订单'
        verbose_name_plural = verbose_name

    class State(IntegerChoices):
        Paying = 1, "待支付"
        Payed_ToTake = 2, "支付成功-待取货"
        Payed_Taked = 3, "交易关闭-已取货"
        Payed_TakeTimeout = 4, "交易关闭-未取货"
        PayTimeout = 5, "交易关闭-未付款"
        Drawback = 6, "退款"

    order = models.ForeignKey(to="Order", on_delete=models.CASCADE, verbose_name="总订单")
    goods = models.ForeignKey(to="Venue.Goods", on_delete=models.CASCADE, verbose_name="商品")
    state = models.IntegerField(choices=State.choices, verbose_name="状态")

    price = models.FloatField(verbose_name="价格")
    number = models.IntegerField(verbose_name="数量")
    verify = models.IntegerField(null=True,verbose_name="校验码")
    getTime = models.DateTimeField(null=True, verbose_name="收货时间")
    message = models.CharField(max_length=200, verbose_name="留言")

    drawback = models.ForeignKey(to="Drawback", null=True, on_delete=models.CASCADE, verbose_name="退款")


    def capitalInfo(self):
        """ 资金流水账 """
        return {
            "oid": self.order_id,
            "id": self.id,
            "goodsId": self.goods_id,
            "price": self.price,
            "number": self.number,
            "createTime": self.createTime
        }
    def Info(self):
        self.checkTimeout()
        return {
            "id": self.id,
            "goods": self.goods.Info(),
            "state": self.state,
            "price": self.price,
            "number": self.number,
            "getTime": self.getTime,
            "verify": self.verify,
            "message": self.message,
            "createTime": self.createTime,
            "drawback": self.drawback.Info() if self.drawback else None
        }

    @classmethod
    def create(cls, user, goods,number, message='',order=None):
        from User.models import Order
        venue = goods.venue
        if not order:
            order = Order.create(user, venue, type=Order.OrderType.Goods)
        orderGoods = cls(order=order, goods=goods, state=cls.State.Paying, price=goods.price, number=number, message=message)
        orderGoods.save()
        return order

    def pay(self):
        """ 支付 """
        if self.state == self.State.Paying:
            self.state = self.State.Payed_ToTake
            self.verify = self.getVerify()
            self.save()

    def checkTimeout(self):
        """ 超时 """
        if self.state == self.State.Paying:
            over = self.createTime + datetime.timedelta(minutes=30)
            now = datetime.datetime.now()
            if over < now:
                self.state = self.State.PayTimeout
                self.save()

    @classmethod
    def getVerify(cls):
        """ 获取校验码 """
        return random.randint(1000, 9999)

    def verifyCode(self,verifyCode=''):
        """ 取货 """
        if self.state == self.State.Payed_ToTake:
            if self.verify == verifyCode:
                self.state = self.State.Payed_Taked
                self.getTime = datetime.datetime.now()
                self.save()
                return True
        return False

    def canDrawback(self):
        if self.state == self.State.Payed_ToTake:
            return True
        return False

    def orderDrawback(self, user, message):
        """ 商品订单退款 """
        from User.models import Drawback

        self.state = self.State.Drawback
        self.save()
        price = self.price * self.number
        Drawback.create(user=user, price=price, message=message)
